/*
 * $Id$
 * $HeadURL$
 *
 * ==============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jettyrunner.server;

/**
 * @author Andrei Solntsev
 * @version $Rev: 000 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
 */
public class ClassUtils
{
	protected static final String CLASS_VERSION = "$Revision: 1.2 $ $Author: asolntsev $";

	/**
	 * Method returns code source of given class.
	 * This is URL of classpath folder, zip or jar file.
	 * If code source is unknown, returns null (for example, for classes java.io.*).
	 *
	 * @param clazz	For example, <code>hireright.sdk.db.CConnection.class</code> or
	 * 							<code>fiorano.tifosi.tps.rtl.Argument.class</code>
	 * @return for example, <code>"file:/C:/jdev10/jdev/mywork/HireRight/ESB%20Services/classes/"</code>
	 * 							or <code>"file:/C:/works/projects/ESB/sdk/java/fiorano/SPRTL.zip"</code>
	 */
	public static String getCodeSource(Class<?> clazz)
	{
		if (clazz == null ||
				clazz.getProtectionDomain() == null ||
				clazz.getProtectionDomain().getCodeSource() == null ||
				clazz.getProtectionDomain().getCodeSource().getLocation() == null)
			return null;

		return clazz.getProtectionDomain().getCodeSource().getLocation().toString();
	}

	public static String getCodeSource(String sClassName)
	{
		return getCodeSource(sClassName, Thread.currentThread().getContextClassLoader());
	}

	/**
	 * @see #getCodeSource(Class)
	 * @param sClassName Full name of class - for example, "oracle.jdbc.OracleDriver"
	 * @return error message if unable to initialize given class by name
	 * @since Nov 6, 2006
	 */
	public static String getCodeSource(String sClassName, ClassLoader cl)
	{
		if (sClassName == null)
			return null;
		try
		{
			Class<?> clazz = Class.forName(sClassName, false, cl);
			return getCodeSource(clazz);
		}
		catch (Throwable e)
		{
			return e.toString();
		}
	}
}
